﻿#include "GUILoadCaseDialog.h"
#include "ui_GUILoadCaseDialog.h"

#include "FITK_Kernel/FITKCore/FITKOperatorRepo.h"
#include "FITK_Kernel/FITKAppFramework/FITKAppFramework.h"
#include "FITK_Kernel/FITKAppFramework/FITKGlobalData.h"

#include "FITK_Component/FITKAcousticsPhysics/FITKAcousticsSolverLoadCase.h"
#include "FITK_Component/FITKAcousticsPhysics/FITKAcousticsPhysics.h"
#include "FITK_Component/FITKAcousticsPhysics/FITKAcousticsLoadManager.h"

#include <QMessageBox>

#define _DATAOBJIDCOLUMN_ 1
#define _DATAOBJID_ 2
#define _DATAOBJCOLUMN_ 0
#define _DATAOBJ_ 1

namespace GUI
{
    GUILoadCaseDialog::GUILoadCaseDialog(Core::FITKActionOperator* oper, QWidget* parent /*= nullptr*/) :
        GUIDialogBase(parent),
        _loadCaseObjID(-1),
        _oper(oper),
        _isCreate(true),
        _ui(new Ui::GUILoadCaseDialog)
    {
        _ui->setupUi(this);
        // 设置对话框关闭时自动删除
        setAttribute(Qt::WA_DeleteOnClose);
        //去掉问号
        Qt::WindowFlags flags = windowFlags();
        flags &= ~Qt::WindowContextHelpButtonHint;
        setWindowFlags(flags);
        //初始化图片
        this->initImage();
        //初始化数据
        this->init();
    }
    GUILoadCaseDialog::GUILoadCaseDialog(int groupObjID, Core::FITKActionOperator* oper, QWidget* parent /*= nullptr*/) :
        GUIDialogBase(parent),
        _loadCaseObjID(groupObjID),
        _oper(oper),
        _isCreate(false),
        _ui(new Ui::GUILoadCaseDialog)
    {
        _ui->setupUi(this);
        // 设置对话框关闭时自动删除
        setAttribute(Qt::WA_DeleteOnClose);
        //去掉问号
        Qt::WindowFlags flags = windowFlags();
        flags &= ~Qt::WindowContextHelpButtonHint;
        setWindowFlags(flags);
        //初始化图片
        this->initImage();
        //初始化数据
        this->init();
    }
    GUILoadCaseDialog::~GUILoadCaseDialog()
    {
        if (_ui) {
            delete _ui;
            _ui = nullptr;
        }
    }

    void GUILoadCaseDialog::on_pushButton_Add_clicked()
    {
        // 获取当前选中的TreeWidget节点
        QTreeWidgetItem *currentItem = _ui->treeWidget_Network->currentItem();
        if (!currentItem) return;
        // 检查节点是否有setData关联的数据
        if (!currentItem->data(_DATAOBJIDCOLUMN_, _DATAOBJID_).isValid()) return;
        //获取载荷管理器
        Acoustics::FITKAcousticsPhysics* physicsData = Acoustics::FITKAcousticsPhysics::GetAcousticsPhysicsFromFrame();
        if (!physicsData) return;
        Acoustics::FITKAcousticsLoadManager* loadManager = physicsData->getFITKAcousticsLoadManager();
        if (!loadManager) return;
        // 获取当前选中节点的_DATAOBJID_
        int currentDataObjId = currentItem->data(_DATAOBJIDCOLUMN_, _DATAOBJID_).toInt();
        // 遍历TableWidget中的所有项，检查是否已经存在相同_DATAOBJID_的项
        int rowCount = _ui->tableWidget_Element->rowCount();
        for (int i = 0; i < rowCount; ++i)
        {
            QTableWidgetItem *item = _ui->tableWidget_Element->item(i, 0);
            if (item && item->data(_DATAOBJID_).toInt() == currentDataObjId) return;
        }
        //获取载荷数据
        Acoustics::FITKAcousticsAbstractLoad* loadData = loadManager->getDataByID(currentDataObjId);
        if (!loadData) return;
        //获取连接名称
        QString connectName = loadData->getConnectionObjName();
        if (connectName.isEmpty()) return;
        // 添加节点到TableWidget
        int row = _ui->tableWidget_Element->rowCount();
        _ui->tableWidget_Element->setRowCount(row + 1);
        QTableWidgetItem *itemName = new QTableWidgetItem(loadData->getDataObjectName());
        // 设置左对齐
        _ui->tableWidget_Element->setItem(row, 0, itemName);
        _ui->tableWidget_Element->setItem(row, 1, new QTableWidgetItem(connectName));

        // 保存setData关联的数据
        itemName->setData(_DATAOBJID_, currentItem->data(_DATAOBJIDCOLUMN_, _DATAOBJID_));
        // 自动调整列宽以适应内容
        _ui->tableWidget_Element->resizeColumnsToContents();
        // 从TreeWidget中隐藏当前节点
        currentItem->setHidden(true);
    }

    void GUILoadCaseDialog::on_pushButton_Remove_clicked()
    {
        // 获取当前选中的 TableWidget 行
        int currentRow = _ui->tableWidget_Element->currentRow();
        if (currentRow < 0) return;
        // 获取 TableWidget 中的项
        QTableWidgetItem *item = _ui->tableWidget_Element->item(currentRow, 0);
        if (!item) return;
        // 获取 setData 关联的数据
        int dataObjId = item->data(_DATAOBJID_).toInt();
        // 查找 TreeWidget 中的对应节点
        QTreeWidgetItem *root = _ui->treeWidget_Network->invisibleRootItem();
        QTreeWidgetItem *targetItem = findTreeWidgetItemRecursive(root, dataObjId);

        // 显示节点
        if (targetItem)
            targetItem->setHidden(false);
        // 从 TableWidget 中移除当前行
        _ui->tableWidget_Element->removeRow(currentRow);
    }

    void GUILoadCaseDialog::on_pushButton_OK_clicked()
    {
        //创建动作
        if (_isCreate)
        {
            if (!this->createObjData())
                return;
        }
        //修改动作
        else
        {
            if (!this->editObjData())
                return;
        }
        this->accept();
    }

    void GUILoadCaseDialog::on_pushButton_Cancel_clicked()
    {
        this->close();
    }

    void GUILoadCaseDialog::init()
    {
        // 初始化TableWidget
        _ui->tableWidget_Element->setColumnCount(2);
        _ui->tableWidget_Element->setHorizontalHeaderLabels(QStringList{ "Load", "Connection" });
        // 初始化TreeWidget
        _ui->treeWidget_Network->setColumnCount(1);
        _ui->treeWidget_Network->setHeaderLabel("Loads & Contraints");

        // 为root添加子节点
        QTreeWidgetItem *rootItem = _ui->treeWidget_Network->invisibleRootItem();
        this->initLoadTree(rootItem);
        this->initLoadTable();
        //初始化名称
        Acoustics::FITKAcousticsPhysics* physicsData = FITKAPP->getGlobalData()->getPhysicsData<Acoustics::FITKAcousticsPhysics>();
        if (!physicsData) return;
        Acoustics::FITKSolverLoadCaseManager* loadCaseManager = physicsData->getSolverLoadCaseManager();
        if (!loadCaseManager) return;
        QString name = loadCaseManager->checkName("Load Case-1");
        if (!_isCreate)
        {
            //获取数据
            Acoustics::FITKAcousticsSolverLoadCase* loadCase = loadCaseManager->getDataByID(_loadCaseObjID);
            if (!loadCase) return;
            name = loadCase->getDataObjectName();
        }
        _ui->lineEdit_Name->setText(name);
    }

    void GUILoadCaseDialog::initImage()
    {
        //初始化图像
        _ui->label_Image->setPixmap(QPixmap(":/ToolBar/toolBar/Power.png"));
    }

    void GUILoadCaseDialog::initLoadTree(QTreeWidgetItem* rootItem)
    {
        //创建Power、Constraint子节点
        QTreeWidgetItem *powerItem = new QTreeWidgetItem(rootItem, QStringList{ "Power" });
        QTreeWidgetItem *constraintItem = new QTreeWidgetItem(rootItem, QStringList{ "Constraint" });
        //创建Power下子节点并添加数据
        QTreeWidgetItem *pBeam = new QTreeWidgetItem(powerItem, QStringList{ "Beam" });
        QTreeWidgetItem *pShell = new QTreeWidgetItem(powerItem, QStringList{ "Shell" });
        QTreeWidgetItem *pAcoustic = new QTreeWidgetItem(powerItem, QStringList{ "Acoustic" });
        QTreeWidgetItem *pFE = new QTreeWidgetItem(powerItem, QStringList{ "FE Subsystems" });
        setLoadTreeItems(pBeam, Acoustics::FITKAcousticsAbstractLoad::AcousticsLoadType::PowerSEABeam);
        setLoadTreeItems(pShell, Acoustics::FITKAcousticsAbstractLoad::AcousticsLoadType::PowerSEAShell);
        setLoadTreeItems(pAcoustic, Acoustics::FITKAcousticsAbstractLoad::AcousticsLoadType::PowerSEAAcoustic);
        setLoadTreeItems(pFE, Acoustics::FITKAcousticsAbstractLoad::AcousticsLoadType::PowerFESubsys);
        //创建Constraint下子节点并添加数据
        QTreeWidgetItem *cBeam = new QTreeWidgetItem(constraintItem, QStringList{ "Beam" });
        QTreeWidgetItem *cShell = new QTreeWidgetItem(constraintItem, QStringList{ "Shell" });
        QTreeWidgetItem *cAcoustic = new QTreeWidgetItem(constraintItem, QStringList{ "Acoustic" });
        QTreeWidgetItem *cFE = new QTreeWidgetItem(constraintItem, QStringList{ "FE Subsystems" });
        setLoadTreeItems(cBeam, Acoustics::FITKAcousticsAbstractLoad::AcousticsLoadType::ConstraintSEABeam);
        setLoadTreeItems(cShell, Acoustics::FITKAcousticsAbstractLoad::AcousticsLoadType::ConstraintSEAShell);
        setLoadTreeItems(cAcoustic, Acoustics::FITKAcousticsAbstractLoad::AcousticsLoadType::ConstraintSEAAcoustic);
        setLoadTreeItems(cFE, Acoustics::FITKAcousticsAbstractLoad::AcousticsLoadType::ConstraintFESubsys);
        //创建其他子节点并添加数据
        QTreeWidgetItem *ponitForceMoments = new QTreeWidgetItem(rootItem, QStringList{ "Ponit Force & Moments" });
        QTreeWidgetItem *HVACNoiseItem = new QTreeWidgetItem(rootItem, QStringList{ "HVACNoise" });
        QTreeWidgetItem *monopoleItem = new QTreeWidgetItem(rootItem, QStringList{ "Monopole" });
        setLoadTreeItems(ponitForceMoments, Acoustics::FITKAcousticsAbstractLoad::AcousticsLoadType::ExcitationForceMoments);
        setLoadTreeItems(HVACNoiseItem, Acoustics::FITKAcousticsAbstractLoad::AcousticsLoadType::ImportNoiseHVAC);
        setLoadTreeItems(monopoleItem, Acoustics::FITKAcousticsAbstractLoad::AcousticsLoadType::ExcitationMonopole);
    }

    void GUILoadCaseDialog::initLoadTable()
    {
        Acoustics::FITKAcousticsPhysics* physicsData = FITKAPP->getGlobalData()->getPhysicsData<Acoustics::FITKAcousticsPhysics>();
        if (!physicsData) return;
        Acoustics::FITKSolverLoadCaseManager* loadCaseManager = physicsData->getSolverLoadCaseManager();
        Acoustics::FITKAcousticsLoadManager* loadManager = physicsData->getFITKAcousticsLoadManager();
        if (!loadManager || !loadCaseManager) return;
        //获取数据
        Acoustics::FITKAcousticsSolverLoadCase* loadCase = loadCaseManager->getDataByID(_loadCaseObjID);
        if (!loadCase) return;
        QList<int> loadIDs = loadCase->getLoadIDs();
        for (int objID : loadIDs)
        {
            //获取载荷数据
            Acoustics::FITKAcousticsAbstractLoad* loadData = loadManager->getDataByID(objID);
            if (!loadData) continue;
            //获取连接名称
            QString connectName = loadData->getConnectionObjName();
            if (connectName.isEmpty()) continue;
            int row = _ui->tableWidget_Element->rowCount();
            _ui->tableWidget_Element->setRowCount(row + 1);
            QTableWidgetItem *itemName = new QTableWidgetItem(loadData->getDataObjectName());
            itemName->setData(_DATAOBJID_, objID);
            // 设置左对齐
            _ui->tableWidget_Element->setItem(row, 0, itemName);
            _ui->tableWidget_Element->setItem(row, 1, new QTableWidgetItem(connectName));
        }
        // 自动调整列宽以适应内容
        _ui->tableWidget_Element->resizeColumnsToContents();
    }

    void GUILoadCaseDialog::setLoadTreeItems(QTreeWidgetItem *geometryItem, int type)
    {
        Acoustics::FITKAcousticsAbstractLoad::AcousticsLoadType loadType = (Acoustics::FITKAcousticsAbstractLoad::AcousticsLoadType)type;
        Acoustics::FITKAcousticsPhysics* physicsData = Acoustics::FITKAcousticsPhysics::GetAcousticsPhysicsFromFrame();
        if (physicsData == nullptr) return;
        Acoustics::FITKSolverLoadCaseManager* loadCaseManager = physicsData->getSolverLoadCaseManager();
        Acoustics::FITKAcousticsLoadManager* loadManager = physicsData->getFITKAcousticsLoadManager();
        if (!loadManager || !loadCaseManager) return;
        //获取载荷数据和载荷工况数据
        QList< Acoustics::FITKAcousticsAbstractLoad*> loadList = loadManager->getLoadByType(loadType);
        if (loadList.isEmpty()) return;
        QList<int> loadIDs;
        Acoustics::FITKAcousticsSolverLoadCase* loadCase = loadCaseManager->getDataByID(_loadCaseObjID);
        if (loadCase)
            loadIDs = loadCase->getLoadIDs();
        for (QList< Acoustics::FITKAcousticsAbstractLoad*>::iterator iter = loadList.begin(); iter != loadList.end(); ++iter)
        {
            if (!(*iter)) continue;
            QTreeWidgetItem *item = new QTreeWidgetItem(geometryItem, QStringList{ (*iter)->getDataObjectName() });
            int loadID = (*iter)->getDataObjectID();
            // 使用setData关联数据
            item->setData(_DATAOBJIDCOLUMN_, _DATAOBJID_, loadID);
            if (loadIDs.contains(loadID))
                item->setHidden(false);
        }
    }

    QTreeWidgetItem* GUILoadCaseDialog::findTreeWidgetItemRecursive(QTreeWidgetItem *item, int objID)
    {
        if (!item) return nullptr;
        if (item->data(_DATAOBJIDCOLUMN_, _DATAOBJID_).isValid() && item->data(_DATAOBJIDCOLUMN_, _DATAOBJID_).toInt() == objID)
            return item;
        //遍历子树节点
        int count = item->childCount();
        for (int i = 0; i < count; ++i)
        {
            QTreeWidgetItem* childItem = item->child(i);
            if (!childItem)continue;
            QTreeWidgetItem * nodeItem = findTreeWidgetItemRecursive(childItem, objID);
            if (nodeItem) return nodeItem;
        }
        return nullptr;
    }

    bool GUILoadCaseDialog::createObjData()
    {
        //获取载荷工况管理器
        Acoustics::FITKAcousticsPhysics* physicsData = FITKAPP->getGlobalData()->getPhysicsData<Acoustics::FITKAcousticsPhysics>();
        if (!physicsData) return false;
        Acoustics::FITKSolverLoadCaseManager* loadCaseManager = physicsData->getSolverLoadCaseManager();
        if (!loadCaseManager) return false;
        //获取名称-查重处理
        QString name = _ui->lineEdit_Name->text();
        if (loadCaseManager->getDataByName(name)) {
            QMessageBox::warning(this, "", tr("\"%1\" already exists and cannot be overwritten.").arg(name), QMessageBox::Ok);
            return false;
        }
        //创建载荷工况
        Acoustics::FITKAcousticsSolverLoadCase* loadCase = new Acoustics::FITKAcousticsSolverLoadCase();
        loadCase->setDataObjectName(name);
        //设置界面数据
        this->getDataFormWidget(loadCase);
        //设置数据
        loadCaseManager->appendDataObj(loadCase);
        return true;
    }

    bool GUILoadCaseDialog::editObjData()
    {
        //获取载荷工况管理器
        Acoustics::FITKAcousticsPhysics* physicsData = FITKAPP->getGlobalData()->getPhysicsData<Acoustics::FITKAcousticsPhysics>();
        if (!physicsData) return false;
        Acoustics::FITKSolverLoadCaseManager* loadCaseManager = physicsData->getSolverLoadCaseManager();
        if (!loadCaseManager) return false;
        //获取数据
        Acoustics::FITKAcousticsSolverLoadCase* loadCase = loadCaseManager->getDataByID(_loadCaseObjID);
        if (!loadCase) return false;
        //获取名称-查重处理
        QString name = _ui->lineEdit_Name->text();
        if (name != loadCase->getDataObjectName())
            if (loadCaseManager->getDataByName(name)) {
                QMessageBox::warning(this, "", tr("\"%1\" already exists and cannot be overwritten.").arg(name), QMessageBox::Ok);
                return false;
            }
        loadCase->setDataObjectName(name);
        //设置界面数据
        this->getDataFormWidget(loadCase);
        return true;
    }

    void GUILoadCaseDialog::getDataFormWidget(Acoustics::FITKAcousticsSolverLoadCase* loadCase)
    {
        if (!loadCase) return;
        // 清空原有数据
        loadCase->clearLoad();
        //设置数据
        int rowCount = _ui->tableWidget_Element->rowCount();
        for (int i = 0; i < rowCount; ++i)
        {
            QTableWidgetItem *item = _ui->tableWidget_Element->item(i, 0);
            if (item == nullptr) continue;
            int objID = item->data(_DATAOBJID_).toInt();
            loadCase->addLoad(objID);
        }
    }
}
